{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 长短期记忆网络（LSTM）\n",
    ":label:`sec_lstm`\n",
    "\n",
    "长期以来，隐变量模型存在着长期信息保存和短期输入缺失的问题。\n",
    "解决这一问题的最早方法之一是长短期存储器（long short-term memory，LSTM）\n",
    " :cite:`Hochreiter.Schmidhuber.1997`。\n",
    "它有许多与门控循环单元（ :numref:`sec_gru`）一样的属性。\n",
    "有趣的是，长短期记忆网络的设计比门控循环单元稍微复杂一些，\n",
    "却比门控循环单元早诞生了近20年。\n",
    "\n",
    "## 门控记忆元\n",
    "\n",
    "可以说，长短期记忆网络的设计灵感来自于计算机的逻辑门。\n",
    "长短期记忆网络引入了*记忆元*（memory cell），或简称为*单元*（cell）。\n",
    "有些文献认为记忆元是隐状态的一种特殊类型，\n",
    "它们与隐状态具有相同的形状，其设计目的是用于记录附加的信息。\n",
    "为了控制记忆元，我们需要许多门。\n",
    "其中一个门用来从单元中输出条目，我们将其称为*输出门*（output gate）。\n",
    "另外一个门用来决定何时将数据读入单元，我们将其称为*输入门*（input gate）。\n",
    "我们还需要一种机制来重置单元的内容，由*遗忘门*（forget gate）来管理，\n",
    "这种设计的动机与门控循环单元相同，\n",
    "能够通过专用机制决定什么时候记忆或忽略隐状态中的输入。\n",
    "让我们看看这在实践中是如何运作的。\n",
    "\n",
    "### 输入门、忘记门和输出门\n",
    "\n",
    "就如在门控循环单元中一样，\n",
    "当前时间步的输入和前一个时间步的隐状态\n",
    "作为数据送入长短期记忆网络的门中，\n",
    "如 :numref:`lstm_0`所示。\n",
    "它们由三个具有sigmoid激活函数的全连接层处理，\n",
    "以计算输入门、遗忘门和输出门的值。\n",
    "因此，这三个门的值都在$(0, 1)$的范围内。\n",
    "\n",
    "![长短期记忆模型中的输入门、遗忘门和输出门](https://d2l.ai/_images/lstm-0.svg)\n",
    ":label:`lstm_0`\n",
    "\n",
    "我们来细化一下长短期记忆网络的数学表达。\n",
    "假设有$h$个隐藏单元，批量大小为$n$，输入数为$d$。\n",
    "因此，输入为$\\mathbf{X}_t \\in \\mathbb{R}^{n \\times d}$，\n",
    "前一时间步的隐状态为$\\mathbf{H}_{t-1} \\in \\mathbb{R}^{n \\times h}$。\n",
    "相应地，时间步$t$的门被定义如下：\n",
    "输入门是$\\mathbf{I}_t \\in \\mathbb{R}^{n \\times h}$，\n",
    "遗忘门是$\\mathbf{F}_t \\in \\mathbb{R}^{n \\times h}$，\n",
    "输出门是$\\mathbf{O}_t \\in \\mathbb{R}^{n \\times h}$。\n",
    "它们的计算方法如下：\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\mathbf{I}_t &= \\sigma(\\mathbf{X}_t \\mathbf{W}_{xi} + \\mathbf{H}_{t-1} \\mathbf{W}_{hi} + \\mathbf{b}_i),\\\\\n",
    "\\mathbf{F}_t &= \\sigma(\\mathbf{X}_t \\mathbf{W}_{xf} + \\mathbf{H}_{t-1} \\mathbf{W}_{hf} + \\mathbf{b}_f),\\\\\n",
    "\\mathbf{O}_t &= \\sigma(\\mathbf{X}_t \\mathbf{W}_{xo} + \\mathbf{H}_{t-1} \\mathbf{W}_{ho} + \\mathbf{b}_o),\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "其中$\\mathbf{W}_{xi}, \\mathbf{W}_{xf}, \\mathbf{W}_{xo} \\in \\mathbb{R}^{d \\times h}$\n",
    "和$\\mathbf{W}_{hi}, \\mathbf{W}_{hf}, \\mathbf{W}_{ho} \\in \\mathbb{R}^{h \\times h}$是权重参数，\n",
    "$\\mathbf{b}_i, \\mathbf{b}_f, \\mathbf{b}_o \\in \\mathbb{R}^{1 \\times h}$是偏置参数。\n",
    "\n",
    "### 候选记忆元\n",
    "\n",
    "由于还没有指定各种门的操作，所以先介绍*候选记忆元*（candidate memory cell）\n",
    "$\\tilde{\\mathbf{C}}_t \\in \\mathbb{R}^{n \\times h}$。\n",
    "它的计算与上面描述的三个门的计算类似，\n",
    "但是使用$\\tanh$函数作为激活函数，函数的值范围为$(-1, 1)$。\n",
    "下面导出在时间步$t$处的方程：\n",
    "\n",
    "$$\\tilde{\\mathbf{C}}_t = \\text{tanh}(\\mathbf{X}_t \\mathbf{W}_{xc} + \\mathbf{H}_{t-1} \\mathbf{W}_{hc} + \\mathbf{b}_c),$$\n",
    "\n",
    "其中$\\mathbf{W}_{xc} \\in \\mathbb{R}^{d \\times h}$和\n",
    "$\\mathbf{W}_{hc} \\in \\mathbb{R}^{h \\times h}$是权重参数，\n",
    "$\\mathbf{b}_c \\in \\mathbb{R}^{1 \\times h}$是偏置参数。\n",
    "\n",
    "候选记忆元的如 :numref:`lstm_1`所示。\n",
    "\n",
    "![长短期记忆模型中的候选记忆元](https://d2l.ai/_images/lstm-1.svg)\n",
    ":label:`lstm_1`\n",
    "\n",
    "### 记忆元\n",
    "\n",
    "在门控循环单元中，有一种机制来控制输入和遗忘（或跳过）。\n",
    "类似地，在长短期记忆网络中，也有两个门用于这样的目的：\n",
    "输入门$\\mathbf{I}_t$控制采用多少来自$\\tilde{\\mathbf{C}}_t$的新数据，\n",
    "而遗忘门$\\mathbf{F}_t$控制保留多少过去的\n",
    "记忆元$\\mathbf{C}_{t-1} \\in \\mathbb{R}^{n \\times h}$的内容。\n",
    "使用按元素乘法，得出：\n",
    "\n",
    "$$\\mathbf{C}_t = \\mathbf{F}_t \\odot \\mathbf{C}_{t-1} + \\mathbf{I}_t \\odot \\tilde{\\mathbf{C}}_t.$$\n",
    "\n",
    "如果遗忘门始终为$1$且输入门始终为$0$，\n",
    "则过去的记忆元$\\mathbf{C}_{t-1}$\n",
    "将随时间被保存并传递到当前时间步。\n",
    "引入这种设计是为了缓解梯度消失问题，\n",
    "并更好地捕获序列中的长距离依赖关系。\n",
    "\n",
    "这样我们就得到了计算记忆元的流程图，如 :numref:`lstm_2`。\n",
    "\n",
    "![在长短期记忆网络模型中计算记忆元](https://d2l.ai/_images/lstm-2.svg)\n",
    "\n",
    ":label:`lstm_2`\n",
    "\n",
    "### 隐状态\n",
    "\n",
    "最后，我们需要定义如何计算隐状态\n",
    "$\\mathbf{H}_t \\in \\mathbb{R}^{n \\times h}$，\n",
    "这就是输出门发挥作用的地方。\n",
    "在长短期记忆网络中，它仅仅是记忆元的$\\tanh$的门控版本。\n",
    "这就确保了$\\mathbf{H}_t$的值始终在区间$(-1, 1)$内：\n",
    "\n",
    "$$\\mathbf{H}_t = \\mathbf{O}_t \\odot \\tanh(\\mathbf{C}_t).$$\n",
    "\n",
    "只要输出门接近$1$，我们就能够有效地将所有记忆信息传递给预测部分，\n",
    "而对于输出门接近$0$，我们只保留记忆元内的所有信息，而不需要更新隐状态。\n",
    "\n",
    " :numref:`lstm_3`提供了数据流的图形化演示。\n",
    "\n",
    "![在长短期记忆模型中计算隐状态](https://d2l.ai/_images/lstm-3.svg)\n",
    ":label:`lstm_3`\n",
    "\n",
    "## 从零开始实现\n",
    "\n",
    "现在，我们从零开始实现长短期记忆网络。\n",
    "与 :numref:`sec_rnn_scratch`中的实验相同，\n",
    "我们首先加载时光机器数据集。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java\n",
    "%load ../utils/PlotUtils.java\n",
    "\n",
    "%load ../utils/StopWatch.java\n",
    "%load ../utils/Accumulator.java\n",
    "%load ../utils/Animator.java\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/timemachine/Vocab.java\n",
    "%load ../utils/timemachine/RNNModel.java\n",
    "%load ../utils/timemachine/RNNModelScratch.java\n",
    "%load ../utils/timemachine/TimeMachine.java\n",
    "%load ../utils/timemachine/TimeMachineDataset.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int batchSize = 32;\n",
    "int numSteps = 35;\n",
    "\n",
    "TimeMachineDataset dataset =\n",
    "        new TimeMachineDataset.Builder()\n",
    "                .setManager(manager)\n",
    "                .setMaxTokens(10000)\n",
    "                .setSampling(batchSize, false)\n",
    "                .setSteps(numSteps)\n",
    "                .build();\n",
    "dataset.prepare();\n",
    "Vocab vocab = dataset.getVocab();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 初始化模型参数\n",
    "\n",
    "接下来，我们需要定义和初始化模型参数。\n",
    "如前所述，超参数`numHiddens`定义隐藏单元的数量。\n",
    "我们按照标准差$0.01$的高斯分布初始化权重，并将偏置项设为$0$。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static NDList getLSTMParams(int vocabSize, int numHiddens, Device device) {\n",
    "    int numInputs = vocabSize;\n",
    "    int numOutputs = vocabSize;\n",
    "\n",
    "    // Input gate parameters\n",
    "    NDList temp = three(numInputs, numHiddens, device);\n",
    "    NDArray W_xi = temp.get(0);\n",
    "    NDArray W_hi = temp.get(1);\n",
    "    NDArray b_i = temp.get(2);\n",
    "\n",
    "    // Forget gate parameters\n",
    "    temp = three(numInputs, numHiddens, device);\n",
    "    NDArray W_xf = temp.get(0);\n",
    "    NDArray W_hf = temp.get(1);\n",
    "    NDArray b_f = temp.get(2);\n",
    "\n",
    "    // Output gate parameters\n",
    "    temp = three(numInputs, numHiddens, device);\n",
    "    NDArray W_xo = temp.get(0);\n",
    "    NDArray W_ho = temp.get(1);\n",
    "    NDArray b_o = temp.get(2);\n",
    "\n",
    "    // Candidate memory cell parameters\n",
    "    temp = three(numInputs, numHiddens, device);\n",
    "    NDArray W_xc = temp.get(0);\n",
    "    NDArray W_hc = temp.get(1);\n",
    "    NDArray b_c = temp.get(2);\n",
    "\n",
    "    // Output layer parameters\n",
    "    NDArray W_hq = normal(new Shape(numHiddens, numOutputs), device);\n",
    "    NDArray b_q = manager.zeros(new Shape(numOutputs), DataType.FLOAT32, device);\n",
    "\n",
    "    // Attach gradients\n",
    "    NDList params =\n",
    "            new NDList(\n",
    "                    W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc, b_c, W_hq,\n",
    "                    b_q);\n",
    "    for (NDArray param : params) {\n",
    "        param.setRequiresGradient(true);\n",
    "    }\n",
    "    return params;\n",
    "}\n",
    "\n",
    "public static NDArray normal(Shape shape, Device device) {\n",
    "    return manager.randomNormal(0, 0.01f, shape, DataType.FLOAT32, device);\n",
    "}\n",
    "\n",
    "public static NDList three(int numInputs, int numHiddens, Device device) {\n",
    "    return new NDList(\n",
    "            normal(new Shape(numInputs, numHiddens), device),\n",
    "            normal(new Shape(numHiddens, numHiddens), device),\n",
    "            manager.zeros(new Shape(numHiddens), DataType.FLOAT32, device));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定义模型\n",
    "\n",
    "在初始化函数中，\n",
    "长短期记忆网络的隐状态需要返回一个*额外*的记忆元，\n",
    "单元的值为0，形状为（批量大小，隐藏单元数）。\n",
    "因此，我们得到以下的状态初始化。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static NDList initLSTMState(int batchSize, int numHiddens, Device device) {\n",
    "    return new NDList(\n",
    "            manager.zeros(new Shape(batchSize, numHiddens), DataType.FLOAT32, device),\n",
    "            manager.zeros(new Shape(batchSize, numHiddens), DataType.FLOAT32, device));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实际模型的定义与我们前面讨论的一样：\n",
    "提供三个门和一个额外的记忆元。\n",
    "请注意，只有隐状态才会传递到输出层，\n",
    "而记忆元$\\mathbf{C}_t$不直接参与输出计算。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static Pair<NDArray, NDList> lstm(NDArray inputs, NDList state, NDList params) {\n",
    "    NDArray W_xi = params.get(0);\n",
    "    NDArray W_hi = params.get(1);\n",
    "    NDArray b_i = params.get(2);\n",
    "\n",
    "    NDArray W_xf = params.get(3);\n",
    "    NDArray W_hf = params.get(4);\n",
    "    NDArray b_f = params.get(5);\n",
    "\n",
    "    NDArray W_xo = params.get(6);\n",
    "    NDArray W_ho = params.get(7);\n",
    "    NDArray b_o = params.get(8);\n",
    "\n",
    "    NDArray W_xc = params.get(9);\n",
    "    NDArray W_hc = params.get(10);\n",
    "    NDArray b_c = params.get(11);\n",
    "\n",
    "    NDArray W_hq = params.get(12);\n",
    "    NDArray b_q = params.get(13);\n",
    "\n",
    "    NDArray H = state.get(0);\n",
    "    NDArray C = state.get(1);\n",
    "    NDList outputs = new NDList();\n",
    "    NDArray X, Y, I, F, O, C_tilda;\n",
    "    for (int i = 0; i < inputs.size(0); i++) {\n",
    "        X = inputs.get(i);\n",
    "        I = Activation.sigmoid(X.dot(W_xi).add(H.dot(W_hi).add(b_i)));\n",
    "        F = Activation.sigmoid(X.dot(W_xf).add(H.dot(W_hf).add(b_f)));\n",
    "        O = Activation.sigmoid(X.dot(W_xo).add(H.dot(W_ho).add(b_o)));\n",
    "        C_tilda = Activation.tanh(X.dot(W_xc).add(H.dot(W_hc).add(b_c)));\n",
    "        C = F.mul(C).add(I.mul(C_tilda));\n",
    "        H = O.mul(Activation.tanh(C));\n",
    "        Y = H.dot(W_hq).add(b_q);\n",
    "        outputs.add(Y);\n",
    "    }\n",
    "    return new Pair(\n",
    "            outputs.size() > 1 ? NDArrays.concat(outputs) : outputs.get(0), new NDList(H, C));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 训练和预测\n",
    "\n",
    "让我们通过实例化 :numref:`sec_rnn_scratch`中\n",
    "引入的`RNNModelScratch`类来训练一个长短期记忆网络，\n",
    "就如我们在 :numref:`sec_gru`中所做的一样。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int vocabSize = vocab.length();\n",
    "int numHiddens = 256;\n",
    "Device device = manager.getDevice();\n",
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 500);\n",
    "\n",
    "int lr = 1;\n",
    "\n",
    "Functions.TriFunction<Integer, Integer, Device, NDList> getParamsFn =\n",
    "        (a, b, c) -> getLSTMParams(a, b, c);\n",
    "Functions.TriFunction<Integer, Integer, Device, NDList> initLSTMStateFn =\n",
    "        (a, b, c) -> initLSTMState(a, b, c);\n",
    "Functions.TriFunction<NDArray, NDList, NDList, Pair<NDArray, NDList>> lstmFn = (a, b, c) -> lstm(a, b, c);\n",
    "\n",
    "RNNModelScratch model =\n",
    "        new RNNModelScratch(\n",
    "                vocabSize, numHiddens, device, getParamsFn, initLSTMStateFn, lstmFn);\n",
    "TimeMachine.trainCh8(model, dataset, vocab, lr, numEpochs, device, false, manager);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 简洁实现\n",
    "\n",
    "使用高级API，我们可以直接实例化`LSTM`模型。\n",
    "高级API封装了前文介绍的所有配置细节。\n",
    "这段代码的运行速度要快得多，\n",
    "因为它使用的是编译好的运算符而不是Python来处理之前阐述的许多细节。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "LSTM lstmLayer =\n",
    "        LSTM.builder()\n",
    "                .setNumLayers(1)\n",
    "                .setStateSize(numHiddens)\n",
    "                .optReturnState(true)\n",
    "                .optBatchFirst(false)\n",
    "                .build();\n",
    "RNNModel modelConcise = new RNNModel(lstmLayer, vocab.length());\n",
    "TimeMachine.trainCh8(modelConcise, dataset, vocab, lr, numEpochs, device, false, manager);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "长短期记忆网络是典型的具有重要状态控制的隐变量自回归模型。\n",
    "多年来已经提出了其许多变体，例如，多层、残差连接、不同类型的正则化。\n",
    "然而，由于序列的长距离依赖性，训练长短期记忆网络\n",
    "和其他序列模型（例如门控循环单元）的成本是相当高的。\n",
    "在后面的内容中，我们将讲述更高级的替代模型，如transformer。\n",
    "\n",
    "## 小结\n",
    "\n",
    "* 长短期记忆网络有三种类型的门：输入门、遗忘门和输出门。\n",
    "* 长短期记忆网络的隐藏层输出包括“隐状态”和“记忆元”。只有隐状态会传递到输出层，而记忆元完全属于内部信息。\n",
    "* 长短期记忆网络可以缓解梯度消失和梯度爆炸。\n",
    "\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 调整和分析超参数对运行时间、困惑度和输出顺序的影响。\n",
    "1. 你需要如何更改模型以生成适当的单词，而不是字符序列？\n",
    "1. 在给定隐藏层维度的情况下，比较门控循环单元、长短期记忆网络和常规循环神经网络的计算成本。要特别注意训练和推断成本。\n",
    "1. 既然候选记忆元通过使用$\\tanh$函数来确保值范围在$(-1,1)$之间，那么为什么隐状态需要再次使用$\\tanh$函数来确保输出值范围在$(-1,1)$之间呢？\n",
    "1. 实现一个能够基于时间序列进行预测而不是基于字符序列进行预测的长短期记忆网络模型。\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
